package Experiment;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

public class cookies extends HttpServlet {
    String username;
    String passwd;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置服务器端以UTF-8编码进行输出
        resp.setCharacterEncoding("UTF-8");
        //设置浏览器以UTF-8编码进行接收,解决中文乱码问题
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        //获取session的值
        HttpSession hs = req.getSession();
        String name = (String) hs.getAttribute("name");
        String passwd = (String) hs.getAttribute("passwd");
        if (name == null) {   //判断直接访问欢迎界面的用户是否合法（session没有用户名，不是从登录界面进入的）
            String cname = "";
            String cpasswd = "";
            Cookie[] allCookies = req.getCookies();  //获取Cookie
            if (allCookies != null) {
                for (int i = 0; i < allCookies.length; i++) {
                    Cookie temp = allCookies[i];
                    if (temp.getName().equals("name")) {
                        cname = temp.getValue();  //获得cookie中的用户名和密码
                    } else if (temp.getName().equals("passwd")) {
                        cpasswd = temp.getValue();
                    }
                }
            }
            resp.sendRedirect("http://localhost:8080/javaWeb_war_exploded/successCookies.jsp");   //直接登录欢迎界面且cookie中无值，跳转登录界面
        }

        out.println("成功" + name);
        //resp.sendRedirect("http://localhost:8080/javaWeb_war_exploded/successCookies.jsp");
    }
}
